package com.cool.controller.sysmanagecontroller;

import cn.hutool.core.util.IdUtil;
import com.cool.bo.sysmanage.stuff.LoginSuccessResponseDataBo;
import com.cool.bo.sysmanage.stuff.UserLoginBo;
import com.cool.common.CommonResult;
import com.cool.common.ResponseCode;
import com.cool.po.sysmanagepo.StaffPo;
import com.cool.service.sysmanage.StaffService;
import com.cool.utils.ResponseUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 账户控制器
 *
 * @author Jiangmanman
 * @date 2020/07/24
 */
@RestController
@RequestMapping("/system")
@Slf4j
public class StuffController {
    /**
     * 账户接口
     *
     * @date 2020/07/24
     * @see StaffService
     */
    @Resource
    StaffService staffService;

    /**
     * 公共返回结果
     *
     * @date 2020/07/24
     * @see CommonResult
     */
    private CommonResult commonResult = new CommonResult();

    /**
     * 登录
     *
     * @param request     请求
     * @param response    响应
     * @param userLoginBo 用户登录博
     * @return {@link CommonResult }
     * @author Jiangmanman
     * @date 2020/07/25
     */
    @PostMapping("/login")
    public CommonResult login(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestBody UserLoginBo userLoginBo) throws IOException {

        log.debug("session = "+request.getSession().getId());

        StaffPo staffPo =  staffService.selectByAccountMsg(userLoginBo.getUsername(),userLoginBo.getPassword());

        userLoginBo.setStaffId(staffPo.getStaffId());
        boolean isAjax = ResponseUtil.whetherItIsAJAX(request);

        if(Objects.isNull(staffPo)){
            return CommonResult.newCommonResult().setCode(ResponseCode.USER_LOGIN_FAIL).setMsg("登录失败");
        }else {

            Map<String, Object> map= setLoginMessage(request,userLoginBo);

            return CommonResult.newCommonResult().setCode(ResponseCode.USER_LOGIN_SUCCESS).setMsg("登录成功").setData(map);
        }
    }

    /**
     * 设置登录信息
     *
     * @param request 请求
     * @return {@link HashMap<String, Object> }
     * @author Jiangmanman
     * @date 2020/07/26
     */
    private Map<String, Object> setLoginMessage(HttpServletRequest request,UserLoginBo userLoginBo) {
        Map<String, Object> map = new HashMap<>();

        String str = "login";
        map.put("tokenHead",str);
        String simpleUUID = IdUtil.simpleUUID();

        userLoginBo.setToken(str+simpleUUID);
        map.put("token",simpleUUID);

        request.getSession().setAttribute("userLoginBo",userLoginBo);

        return map;
    }


    /**
     * 返回账户信息和访问菜单
     *
     * @param request  请求
     * @param response 响应
     * @return {@link CommonResult }
     * @author Jiangmanman
     * @date 2020/07/25
     */
    @RequestMapping("/info")
    public CommonResult returnToAccountInformationAndAccessMenu(HttpServletRequest request,HttpServletResponse response){
        //判断用户请求头是否携带正确token
        String authorization = request.getHeader("Authorization");

        Object loginObj = request.getSession().getAttribute("userLoginBo");



        if(Objects.isNull(loginObj)){
            return null;
        }
        UserLoginBo userLoginBo = (UserLoginBo)loginObj;
        String tokenStr = userLoginBo.getTokenHead()+userLoginBo.getToken();

        log.info("authorization:"+authorization);
        log.info("tokenStr:"+tokenStr);

        if(Objects.equals(authorization,tokenStr)){
            LoginSuccessResponseDataBo loginSuccessResponseDataBo = new LoginSuccessResponseDataBo();

            List<String> roleList = new ArrayList<>();
            roleList.add("Test");

            loginSuccessResponseDataBo.setRoles(roleList);


            //根据 staff_id 通过 用户-角色中间表 找到 角色,再通过角色找到对应的列表
            List<LoginSuccessResponseDataBo.Menus> list = staffService.selectMsgByStaffId(userLoginBo.getStaffId());


            List<String> listStr =  getUserPermissionByRole(userLoginBo.getStaffId());

            loginSuccessResponseDataBo.setMenus(list);

            loginSuccessResponseDataBo.setIcon("product");

            loginSuccessResponseDataBo.setUsername("pms");

            loginSuccessResponseDataBo.setList(listStr);
            System.out.println("listStr = "+listStr);


            loginSuccessResponseDataBo.setIcon("https://himg.bdimg.com/sys/portraitn/item/5a73544e54e6b998e8a5bfe79aaee89b8b1626");
            return CommonResult.newCommonResult().setCode(ResponseCode.USER_LOGIN_SUCCESS).setMsg("登录成功").setData(loginSuccessResponseDataBo);

        }else {
            LoginSuccessResponseDataBo loginSuccessResponseDataBo = new LoginSuccessResponseDataBo();
            List<String> roleList = new ArrayList<>();
            roleList.add("Test");
            loginSuccessResponseDataBo.setRoles(roleList);
            List<LoginSuccessResponseDataBo.Menus> menusBox = new ArrayList<>();

            loginSuccessResponseDataBo.setMenus(menusBox);
            loginSuccessResponseDataBo.setIcon("product");
            loginSuccessResponseDataBo.setUsername("pms");
            return CommonResult.newCommonResult().setCode(ResponseCode.USER_LOGIN_SUCCESS).setMsg("登录成功").setData(loginSuccessResponseDataBo);
        }

    }

    /**
     * 得到用户的许可
     *
     * @param staffId 员工id
     * @return {@link List<String> }
     * @author Jiangmanman
     * @date 2020/07/30
     */
    private List<String> getUserPermissionByRole(Integer staffId) {

        List<String> list = staffService.getAllPermissionByRoleId(staffId);

        return list;
    }

    /**
     * 分页查询
     *
     * @date 2020/07/27
     * @see Page<StaffPo>
     */
    @GetMapping("/queryPage")
    public CommonResult pagingQuery(StaffPo staffPo){

        return CommonResult.newCommonResult().setCode(ResponseCode.USER_LOGIN_SUCCESS).setMsg("分页查询成功").setData(staffService.accordingToEntityClass(staffPo));
    }

    /**
     * 按主键删除
     *
     * @param id id
     * @return {@link CommonResult }
     * @author Jiangmanman
     * @date 2020/07/27
     */
    @RequestMapping("delete/{id}")
    public CommonResult deleteByPrimaryKey(@PathVariable("id")Integer id){

        Integer len = staffService.accordingToPrimaryKeyAccountRemoved(id);

        if(len > 0){
            return CommonResult.newCommonResult().setCode(ResponseCode.USER_LOGIN_SUCCESS).setMsg("删除成功");
        }else {
            return CommonResult.newCommonResult().setCode(ResponseCode.USER_LOGIN_SUCCESS).setMsg("删除成功");
        }
    }

    /**
     * 根据主键更新
     *
     * @date 2020/07/27
     * @see CommonResult
     */
    @RequestMapping("/update/{id}")
    public CommonResult accordingToPrimaryKeyUpdate(@PathVariable("id")Integer id,@RequestBody StaffPo  staffPo){
        Integer len = staffService.updateAccountInformation(id,staffPo);
        if(len > 0){
            return CommonResult.newCommonResult().setCode(ResponseCode.USER_LOGIN_SUCCESS).setMsg("更新成功");
        }else {
            return CommonResult.newCommonResult().setCode(ResponseCode.USER_LOGIN_FAIL).setMsg("更新成功");
        }
    }

    /**
     * 模糊查询
     *
     * @date 2020/07/27
     * @see PageInfo<StaffPo>
     */
    public CommonResult fuzzyQuery(@RequestBody StaffPo  staffPo){

        return CommonResult.newCommonResult().setCode(ResponseCode.USER_LOGIN_SUCCESS).setMsg("分页查询成功").setData(staffService.fuzzyQuery(staffPo));
    }

    /**
     * 添加账户
     *
     * @param staffPo 账户信息
     * @return {@link CommonResult }
     * @author Jiangmanman
     * @date 2020/07/27
     */
    @PostMapping("/register")
    public CommonResult addAccount(@RequestBody StaffPo  staffPo){
        Integer len =  staffService.insert(staffPo);
        if(len > 0){
            return CommonResult.newCommonResult().setCode(ResponseCode.USER_LOGIN_SUCCESS).setMsg("插入成功");
        }else {
            return CommonResult.newCommonResult().setCode(ResponseCode.USER_LOGIN_FAIL).setMsg("插入失败");
        }
    }

    /**
     * 根据主键更新状态
     *
     * @date 2020/07/27
     * @see CommonResult
     */
    @GetMapping("/updateStatus/{id}")
    public CommonResult accordingToPrimaryKeyUpdateStatus(@PathVariable("id")Integer id, Integer status){
        System.out.println("state = "+status);
        Integer len =  staffService.updateStatusByPrimaryKey(status,id);
        if(len > 0){
            return CommonResult.newCommonResult().setCode(ResponseCode.USER_LOGIN_SUCCESS).setMsg("更新成功");
        }else {
            return CommonResult.newCommonResult().setCode(ResponseCode.USER_LOGIN_FAIL).setMsg("更新失败");
        }
    }

//    /**
//     * 得到所有权限,通过角色id
//     *
//     * @param roleId 角色id
//     * @return {@link CommonResult }
//     * @author Jiangmanman
//     * @date 2020/07/30
//     */
//    @GetMapping("/getAllRole/{id}")
//    public CommonResult getAllPermissionByRoleId(@PathVariable("id")Integer roleId){
//
//        List<String> list = staffService.getAllPermissionByRoleId(roleId);
//
//        return CommonResult.newCommonResult().setCode(ResponseCode.USER_LOGIN_SUCCESS).setMsg("获取权限成功");
//    }
    @PostMapping("/logout")
    public CommonResult logout(HttpServletRequest request,HttpServletResponse response){

        request.getSession().removeAttribute("userLoginBo");

        request.getSession().invalidate();
        SecurityContextHolder.getContext().setAuthentication(null);


         return CommonResult.newCommonResult().setCode(ResponseCode.USER_LOGIN_FAIL).setMsg("成功注销");

    }
}
